<template>
  <div class="app-container">
    <el-form ref="classFrom" :model="classFrom" :rules="rules" label-width="120px">
      <el-form-item label="所属学院" prop="collegeId">
        <CollegeSelect v-model="classFrom.collegeId" />
      </el-form-item>
      <el-form-item label="所属专业" prop="majorId">
        <MajorSelect v-model="classFrom.majorId" :college-id="classFrom.collegeId" />
      </el-form-item>
      <el-form-item label="班级号" prop="id">
        <el-input
          ref="id"
          v-model="classFrom.id"
          placeholder="请输入班级号"
          type="text"
        />
      </el-form-item>
      <el-form-item label="班级名" prop="className">
        <el-input
          ref="className"
          v-model="classFrom.className"
          placeholder="请输入班级名"
          type="text"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAddClass">新增</el-button>
        <el-button @click="handleResetFrom">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { CollegeSelect, MajorSelect } from '@/views/admin/import'
import { classIdPattern } from '@/utils/validate'
import { addClass } from '@/api/admin/class'

export default {
  name: 'AddClass',
  components: { CollegeSelect, MajorSelect },
  data() {
    return {
      classFrom: {
        id: '',
        collegeId: undefined,
        majorId: undefined,
        className: ''
      },
      rules: {
        id: [
          { required: true, message: '请输入班级号', trigger: 'blur' },
          { pattern: classIdPattern, message: '班级号必须为6位数字', trigger: 'blur' }
        ],
        collegeId: [{ required: true, message: '请选择所属学院', trigger: 'blur' }],
        majorId: [{ required: true, message: '请选择所属专业', trigger: 'blur' }],
        className: [
          { required: true, message: '请输入班级名', trigger: 'blur' },
          { min: 2, max: 30, message: '班级名长度不能超过30个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    /**
     * 新增专业信息
     */
    handleAddClass() {
      this.$refs.classFrom.validate(async valid => {
        if (valid) {
          await addClass(this.classFrom)
          this.$message.success('新增成功')
          this.handleResetFrom()
        }
      })
    },
    /**
     * 重置表单
     */
    handleResetFrom() {
      this.$refs.classFrom.resetFields()
    }
  }
}
</script>
